/**
 * 烟花上升阶段音频路径
 */
import upSoundURL from '@/assets/sound/up.mp3';
/**
 * 烟花爆炸音频路径
 */
import boomSoundURL from '@/assets/sound/boom.mp3';
/**
 * 鼠标点击距离左边框距离
 */
let pointX = 0;
/**
 * 鼠标点击距离上边框距离
 */
let pointY = 0;

/**
 * 爆炸初始半径
 */
let pointBeginRadius = 6;
/**
 * 爆炸最大半径
 */
let pointMaxRadius = 300;
/**
 * 爆炸粒子个数
 */
const particleCount = 500;
/**
 * 烟花上升所需要的时间
 */
const pointUpAnimateTime = 1500;
/**
 * 烟花爆炸所需要的时间
 */
const pointBoomAnimateTime = 1500;
/**
 * 自动播放速度
 */
let autoPlaySpeed = 1000;
/**
 * 烟花的颜色
 */
const colors = [
    "#FF3EA5",  // 霓虹粉红
    "#00FF9D",  // 荧光绿
    "#9D00FF",  // 蓝紫色
    "#FF006E",  // 洋红色
    "#00E4FF",  // 荧光蓝
    "#FFD300",  // 荧光黄
    "#FF7F11",  // 亮橙色
    "#7BFF00",  // 青柠色
    "#FF2600",  // 炽热红
    "#00FFEF",  // 蓝绿色
    "#FF00FF",  // 品红色
    "#FF9100",  // 霓虹橙
    "#00B8FF",  // 深天蓝
    "#DB00FF",  // 紫罗兰色
    "#FF2A7F",  // 珊瑚粉
    "#B0FF00"   // 荧光黄绿
];
let interval = null; // 放烟花定时器

export default () => {
    /**
     * 自动播放
     */
    const autoPlay = () => {
        interval = setInterval(() => {
            shootFire({ offsetX: 100 + Math.random() * 1800, offsetY: 100 + Math.random() * 600 })
        }, autoPlaySpeed);
    }
    /**
     * 取消自动播放
     */
    const cancelAutoPlay = () => {
        clearInterval(interval);
    }
    /**
     * 点击发射
     * @param { $event } e 
     */
    const shootFire = async e => {
        // 鼠标点击位置
        pointX = e.offsetX; // 左偏移量
        pointY = e.offsetY; // 右偏移量

        let point = createPoint(pointX)
        document.getElementById("fireworks").appendChild(point);
        await fireUp(point)
        fireBoom(point)
    }

    /**
     * 创建爆炸点
     * @param {*} pointX 
     * @returns 
     */
    const createPoint = (pointX, pointY) => {
        let point = document.createElement("div");
        point.style.position = "absolute";
        point.style.left = `${pointX - pointBeginRadius / 2}px`;
        if (pointY) {
            point.style.top = `${pointY - pointBeginRadius / 2}px`;
        } else {
            point.style.bottom = '0%'
        }
        point.style.width = `${pointBeginRadius}px`;
        point.style.height = `${pointBeginRadius}px`;
        point.style.borderRadius = "50%";
        point.style.backgroundColor = "#ffee8d";

        // 添加尾焰阴影
        // const shadowLayers = [];
        // const baseColor = [255, 215, 0]; // RGB for gold color
        // const steps = 10; // 尾焰的层数
        // const maxBlur = 2; // 最大模糊半径

        // for (let i = 0; i < steps; i++) {
        //     // 计算当前层的颜色透明度
        //     const alpha = 0.8 - (i / steps); // 颜色从不透明到透明
        //     const rgbaColor = `rgba(${baseColor[0]}, ${baseColor[1]}, ${baseColor[2]}, ${alpha})`;
        //     // 计算当前层的模糊半径
        //     const blurRadius = (i + 1) * (maxBlur / steps);
        //     // 计算当前层的偏移量
        //     const offsetX = -(i * 2); // 向左偏移
        //     const offsetY = -(i * 2); // 向上偏移
        //     // 添加阴影层
        //     shadowLayers.push(`${offsetX}px ${offsetY}px ${blurRadius}px ${rgbaColor}`);
        // }
        // point.style.boxShadow = shadowLayers.join(', ');
        return point;
    }

    /**
     * 烟花上升效果
     */
    const fireUp = async (point) => {
        return new Promise(resolve => {
            // 播放上升动画音频
            const audio = new Audio(upSoundURL);
            audio.volume = 0.3; // 音量调整为30%
            audio.play().catch((err) => {
                console.log(err);
            })

            let animation = point.animate([
                {
                    bottom: '0%',
                    opacity: 1,
                    transform: 'rotate(45deg)',
                    offset: 0
                },
                {
                    bottom: 'calc(100% - ' + (pointY + (pointBeginRadius / 2)) + 'px)',
                    opacity: 0.4,
                    transform: 'rotate(45deg)', // 上升旋转
                    offset: 1
                },
            ], {
                duration: pointUpAnimateTime,  // 动画时长
                easing: 'cubic-bezier(0, 0.1, 0, 1)',// 动画的时间函数
                fill: 'forwards' // 指定动画在其活动期间之外的行为，取值可能是 "none", "forwards", "backwards", 或 "both"，默认为 "none"
            })
            // 使用 finished 属性来等待动画完成
            animation.finished.then(() => resolve(true));
        })
    }

    /**
     * 烟花爆炸效果
     */
    const fireBoom = (point) => {
        // 播放爆炸音效
        const audio = new Audio(boomSoundURL);
        audio.volume = 0.3; // 音量调整为30%
        audio.preload = 'auto';
        audio.load();
        audio.play().catch((err) => {
            console.log(err);
        })
        // 获取父容器对象
        const container = document.getElementById("fireworks");
        const containerRect = container.getBoundingClientRect();
        const pointRect = point.getBoundingClientRect();

        // 计算中心点坐标（相对于容器）
        const centerX = pointRect.left - containerRect.left - pointRect.width / 2;
        const centerY = pointRect.top - containerRect.top - pointRect.height / 2;

        let color = colors[Math.floor(Math.random() * colors.length)];
        for (let i = 0; i < particleCount; i++) {
            createParticle(container, centerX, centerY, color);
        }

        // 计算爆炸中心坐标
        point.remove();
    }

    /**
     * 创建爆炸点
     */
    const createParticle = (container, centerX, centerY, color) => {
        const particle = document.createElement("div");
        particle.style.position = "absolute";
        particle.style.left = `${centerX}px`;
        particle.style.top = `${centerY}px`;
        particle.style.width = `${10}px`;
        particle.style.height = `${10}px`;
        particle.style.borderRadius = "50%";
        particle.style.backgroundColor = color;
        // particle.style.boxShadow = "0 0 10px white";
        container.appendChild(particle); // 添加点到容器中
        animateParticle(particle);
    }

    /**
     * 粒子动画
     */
    const animateParticle = (particle) => {
        const angle = Math.random() * Math.PI * 2;

        let distance = Math.random() * pointMaxRadius;
        const dx = Math.cos(angle) * distance;
        const dy = Math.sin(angle) * distance;

        const animation = particle.animate([
            { transform: "translate(0, 0) scale(1)", opacity: 1 },
            { transform: `translate(${dx}px, ${dy}px) scale(0.2)`, opacity: 0 }
        ], {
            duration: pointBoomAnimateTime,
            easing: 'ease-out',
            fill: 'forwards'
        });

        animation.onfinish = () => {
            particle.remove();
        }
    }

    return {
        autoPlay,
        cancelAutoPlay,
        shootFire
    }
}